<template>
    <el-form style="margin-top: 10px;" label-width="160px" label-position="top">
        <el-divider content-position="left">服务器设置</el-divider>
        <el-form-item label="模式">
            <el-radio-group v-model="serverSetting.mode">
                <el-radio :label="ServerModeEnum.CLIENT" :disabled="Constant.mode === 'server'">客户端模式</el-radio>
                <el-radio :label="ServerModeEnum.SERVER">服务器模式</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="服务器地址">
            <el-input style="width: 350px;" :disabled="serverSetting.mode === ServerModeEnum.CLIENT"
                      v-model="serverSetting.url"
                      placeholder="docker不需要填写"/>
        </el-form-item>
        <el-form-item label="token">
            <el-input style="width: 350px;" :disabled="serverSetting.mode === ServerModeEnum.CLIENT"
                      v-model="serverSetting.token"/>
        </el-form-item>
        <el-divider content-position="left">同步设置</el-divider>
        <el-form-item label="模式">
            <el-radio-group v-model="syncSetting.mode">
                <el-radio :label="SyncModeEnum.DISABLE">禁用</el-radio>
                <el-radio :label="SyncModeEnum.SERVER">服务器</el-radio>
                <el-radio :label="SyncModeEnum.FILE">文件</el-radio>
                <el-radio :label="SyncModeEnum.WEBDAV" disabled>WebDav</el-radio>
                <el-radio :label="SyncModeEnum.SFTP" disabled>sftp</el-radio>
            </el-radio-group>
        </el-form-item>

        <!-- 服务器同步 -->
        <el-form-item label="服务器地址"
                      v-if="syncSetting.mode === SyncModeEnum.SERVER && serverSetting.mode !== ServerModeEnum.SERVER">
            <el-input style="width: 350px;" v-model="syncSetting.server.url"
                      placeholder="docker不需要填写"/>
        </el-form-item>
        <el-form-item label="token"
                      v-if="syncSetting.mode === SyncModeEnum.SERVER && serverSetting.mode !== ServerModeEnum.SERVER">
            <el-input style="width: 350px;" v-model="syncSetting.server.token"/>
        </el-form-item>

        <!-- 文件同步 -->
        <el-form-item label="操作" v-if="syncSetting.mode === SyncModeEnum.FILE">
            <el-upload
                class="upload"
                accept="json"
                action=""
                :before-upload="fileSyncUpload"
            >
                <el-button type="primary">上传</el-button>
            </el-upload>
            <el-button type="primary" @click="fileSyncDownload">下载</el-button>
        </el-form-item>
    </el-form>
</template>
<script lang="ts">
import {defineComponent} from "vue";
import {UploadFilled} from "@element-plus/icons-vue";
import {ElLoading, ElNotification, UploadRawFile} from "element-plus";

import ServerModeEnum from "@/enumeration/ServerModeEnum";
import SyncModeEnum from "@/enumeration/SyncModeEnum";

import Constant from "@/global/Constant";
import {baseSearchHistoryService, seniorSearchHistoryService, urlService} from "@/global/BeanFactory";

import useServerStore from "@/store/ServerSettingStore";
import useSyncStore from "@/store/SyncSettingStore";

import ServerSetting from "@/domain/ServerSetting";
import SyncSetting from "@/domain/SyncSetting";

import BrowserUtil from "@/utils/BrowserUtil";
import MessageUtil from "@/utils/MessageUtil";

import SyncAlgorithm from "@/algorithm/SyncAlgorithm";

export default defineComponent({
    name: 'setting-server-sync',
    components: {UploadFilled},
    data: () => ({
        Constant,
        ServerModeEnum,
        SyncModeEnum,
        serverSetting: {
            mode: ServerModeEnum.CLIENT,
            url: '',
            token: ''
        } as ServerSetting,
        syncSetting: {
            mode: SyncModeEnum.DISABLE
        } as SyncSetting,
        edit: false
    }),
    watch: {
        serverSetting() {
            this.edit = true
        }
    },
    created() {
        this.serverSetting = useServerStore().getServer;
        // 服务器模式需要处理
        if (Constant.mode === 'server') {
            // 如果是服务器模式，那么只能是服务器模式
            if (this.serverSetting.mode !== ServerModeEnum.SERVER) {
                // 发送通知
                ElNotification({
                    title: '警告',
                    message: '服务器安装，只能使用服务器模式',
                    type: 'warning',
                })
                useServerStore().setServerMode(ServerModeEnum.SERVER);
                this.serverSetting = useServerStore().getServer;
            }
        }
        this.syncSetting = useSyncStore().getSync;
    },
    methods: {
        // 文件同步上传文件
        fileSyncUpload(rawFile: UploadRawFile) {
            if (typeof FileReader !== 'undefined') {
                let fileReader = new FileReader();
                fileReader.readAsText(rawFile);
                fileReader.onload = function (event: ProgressEvent<FileReader>) {
                    if (event.target) {
                        let content = event.target.result as string;
                        let {url, baseSearchHistory, seniorSearchHistory} = JSON.parse(content);
                        SyncAlgorithm(url, baseSearchHistory, seniorSearchHistory).then(() => {
                            MessageUtil.success('同步成功');
                        }).catch(e => MessageUtil.error('同步失败', e));
                    } else {
                        MessageUtil.error('文件读取失败');
                    }
                };
                fileReader.onerror = function (e: any) {
                    MessageUtil.error('同步失败', e);
                }
            } else {
                MessageUtil.error('文件读取器未定义');
            }
            return false;
        },
        async fileSyncDownload() {
            const loading = ElLoading.service({
                lock: true,
                text: '开始准备数据',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            try {
                loading.setText('获取链接数据')
                let url = await urlService.list();
                loading.setText('获取基础搜索历史');
                let baseSearchHistory = await baseSearchHistoryService.list('');
                loading.setText('获取高级搜索历史');
                let seniorSearchHistory = await seniorSearchHistoryService.list('');
                loading.setText('开始下载');
                console.log(url, baseSearchHistory, seniorSearchHistory)
                BrowserUtil.download(JSON.stringify({
                    url, baseSearchHistory, seniorSearchHistory
                }, null, 4), '数据备份下载.json', 'application/json');
            } catch (e: any) {
                MessageUtil.error('下载失败', e);
            } finally {
                loading.close();
            }
        }
    }
});
</script>
<style scoped>
.upload {
    margin-top: 8px;
    margin-right: 12px;
}
</style>